import 'package:fish_redux/fish_redux.dart';
import 'action.dart';
import 'state.dart';
import '../../../app_files.dart';
import 'package:flutter/material.dart' hide Action;
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:url_launcher/url_launcher.dart';

Effect<SettingViewState> buildEffect() {
  return combineEffects(<Object, Effect<SettingViewState>>{
    SettingViewAction.action: _onAction,
    SettingViewAction.onTap: _onTap,
  });
}

void _onAction(Action action, Context<SettingViewState> ctx) {}

void _onTap(Action action, Context<SettingViewState> ctx) async {
  print(action.payload);
  switch (action.payload) {
    case '清除缓存':
      {
        CommonUtils.showWaitLoading(ctx.context);
        await DefaultCacheManager().emptyCache();
        Navigator.pop(ctx.context);
        CommonUtils.showToast(ctx.context, '清除成功！');
      }
      break;
    case '版本信息':
      {
        CommonUtils.showLoadingDialog(ctx.context);
        ResultData res = await CommonNetWork.versionCheck();
        Navigator.pop(ctx.context);
        if (res.success) {
          List list = res.data;
          if (list.isNotEmpty) {
            var item = list.last;
            String version = CommonUtils.checkNullToString(item['VerVersion']);
            if (version.compareTo(ThemeConfig.version) > 0) {
              int res = await CommonUtils.showVersionDialog(
                ctx.context,
                isForce: item['VerIsForce'],
                message: item['VerUpdateNote'],
                url: item['VerDownloadLink'],
              );
              if (res == 1) {
                launch(CommonUtils.checkNullToString(item['VerDownloadLink']));
              }
              return;
            }
          }
          CommonUtils.showToast(ctx.context, '当前已是最新版本',
              iconType: ToastTipsIconType.info);
        }
      }
      break;
    case '删除账号':
      {
        int ret = await CommonUtils.showOKCanceltView(
            ctx.context, '删除账号后无法登录账号并删除账号相关联信息，是否确认？');
        if (ret == 1) {
          ResultData res = await CommonNetWork.userDel(
              GlobalStore.store.getState().userInfo.userid);
          if (res.success) {
            CommonUtils.showAlertView(ctx.context, "删除成功！").then((r) {
              bus.emit('gomain');
              bus.emit('logout');
              GlobalStore.store.dispatch(GlobalActionCreator.onUserLogout());
              CommonUtils.gotoLoginView(ctx.context);
            });
          } else {
            CommonUtils.showErrorInfo(ctx.context, res.desc);
          }
        }
      }
      break;
  }
}
